<template>
  <div>
    <a-modal
      :visible.sync="visible"
      v-bind="$attrs"
      v-on="$listeners"
      :maskClosable="false"
      :footer="null"
      width="1046px"
      title="人员配置"
      wrapClassName="modal-container"
      @cancel="closeModal()"
    >
      <div class="modal-main" v-loading="pageLoading">
        <a-row :gutter="0">
          <a-form-model ref="form" :model="form">
            <a-col :span="24">
              <a-form-model-item label="节点名称">
                <a-input v-model="form.name" disabled />
              </a-form-model-item>
            </a-col>
          </a-form-model>
        </a-row>
        <a-tabs v-model="activeKey" @change="tabsChange">
          <a-tab-pane key="1" tab="按组织树选择"> </a-tab-pane>
          <a-tab-pane key="2" tab="按人员分组选择"> </a-tab-pane>
        </a-tabs>
        <div class="user-config-modal-body flex">
          <div class="no-choose-container">
            <div class="transfer-header flex">
              未选人员<a-checkbox v-model="allChooseFlag" @change="allChoose()">
                全选
              </a-checkbox>
            </div>
            <div class="transfer-container flex">
              <div class="organization">
                <div class="filter-data" v-if="activeKey == '2'">
                  <div class="input flex">
                    <a-input
                      type="text"
                      v-model="serachGroup"
                      placeholder="请输入人员分组名称"
                      @pressEnter="filterGroup()"
                    />
                    <bj-icon-font
                      type="search"
                      color="#8A8A8C"
                      :size="18"
                      @click="filterGroup()"
                    ></bj-icon-font>
                  </div>
                </div>
                <div class="filter-result" v-loading="orgGroupLoading">
                  <a-empty
                    :image="simpleImage"
                    v-if="
                      (treeData.length == 0 && activeKey == '1') ||
                      (groupData.length == 0 && activeKey == '2')
                    "
                  />
                  <a-tree
                    v-if="activeKey == '1'"
                    v-model="checkedKeys"
                    show-icon
                    :expanded-keys="expandedKeys"
                    :auto-expand-parent="autoExpandParent"
                    :selected-keys="selectedKeys"
                    :tree-data="treeData"
                    :replaceFields="{
                      children: 'childs',
                      title: 'orgName',
                      key: 'id',
                    }"
                    @expand="onExpand"
                    @select="onSelect"
                  >
                    <template slot="custom" slot-scope="{ childs }">
                      <img
                        class="menu-icon"
                        src="@/assets/images/folder.png"
                        v-if="childs"
                      />
                      <img
                        v-else
                        class="menu-icon"
                        src="@/assets/images/file.png"
                      />
                    </template>
                  </a-tree>
                  <div class="group-container" v-else>
                    <div
                      class="group-item"
                      :class="{ 'group-check': groupIndex == index }"
                      v-for="(item, index) in groupData"
                      :key="index"
                      @click="groupCheck(index, item)"
                    >
                      {{ item }}
                    </div>
                  </div>
                </div>
              </div>
              <div class="people">
                <div class="filter-data">
                  <div class="input flex">
                    <a-input
                      type="text"
                      placeholder="请输入姓名"
                      v-model="userName"
                      @pressEnter="filterData()"
                    />
                    <bj-icon-font
                      type="search"
                      color="#8A8A8C"
                      :size="18"
                      @click="filterData()"
                    ></bj-icon-font>
                  </div>
                </div>
                <div class="filter-result" v-loading="userListLoading">
                  <a-empty
                    :image="simpleImage"
                    v-if="peoleOptions.length == 0"
                  />
                  <a-checkbox-group
                    v-model="people"
                    name="checkboxgroup"
                    :options="peoleOptions"
                  />
                </div>
              </div>
            </div>
          </div>
          <div class="transfer-button">
            <div
              class="button"
              :class="people.length == 0 && 'dis'"
              @click="transferData()"
            ></div>
          </div>
          <div class="choose-container">
            <div class="transfer-header flex">
              已选人员
              <span class="clear-all" @click="allClear()">全部清空</span>
            </div>
            <div class="transfer-container">
              <a-empty :image="simpleImage" v-if="hasChoosedUser.length == 0" />
              <div
                class="choosed-people"
                v-for="item in hasChoosedUser"
                :key="item.id"
              >
                <span>{{ item.userName }}</span>
                <span class="colose">
                  <bj-icon-font
                    type="close"
                    color="#fff"
                    :size="12"
                    @click="removeUser(item)"
                  ></bj-icon-font>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <a-button type="default" @click="closeModal()"> 取消 </a-button>
        <a-button
          type="default"
          @click="save()"
          :disabled="hasChoosedUser.length == 0"
        >
          提交并新增人员分组
        </a-button>
        <a-button
          type="primary"
          @click="submit()"
          :loading="loading"
          :disabled="hasChoosedUser.length == 0"
        >
          提交
        </a-button>
      </div>
    </a-modal>
    <!-- 分组名称 -->
    <groupNameModal :visible.sync="groupNameModalVisible" :modal="groupMoadl">
    </groupNameModal>
  </div>
</template>

<script>
import { Empty } from "ant-design-vue";
import groupNameModal from "./groupNameModal";
import { addAttributeByKey, notificationTip } from "@/utils";
import {
  getOrganizationTreeList,
  getOrganizationUserList,
  getGroupList,
  getGroupUserList,
  saveOrEditUserConfig,
  getUserConfigChoosed,
} from "@/api/user-center/flowPathConfig.js";
export default {
  name: "userConfigModal",
  components: {
    groupNameModal,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    modal: {
      type: Object,
      default: {},
    },
  },
  watch: {
    visible: {
      handler(val) {
        this.$emit("update:visible", val);
        if (val) {
          let { tenantCode, name, id } = this.modal;
          this.form = {
            tenantCode,
            name,
            id,
          };
          this.getOrgTreeList();
          this.getChoosedUser();
        }
      },
      immediate: true,
    },
  },
  data() {
    return {
      pageLoading: false,
      loading: false,
      form: {
        tenantCode: "",
        name: "",
        id: "",
      },
      activeKey: "1",
      //组织树/人员分组
      orgGroupLoading: false,
      treeData: [],
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      orgId: "",
      serachGroup: "",
      groupName: "",
      groupData: [],
      groupIndex: null,
      //人员列表
      userName: "",
      people: [],
      peoleOptions: [],
      userListLoading: false,
      //已选人员
      hasChoosedUser: [],
      allChooseFlag: false,
      //组件参数
      groupNameModalVisible: false,
      groupMoadl: {},
    };
  },
  beforeCreate() {
    this.simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
  },
  methods: {
    //tabs切换
    tabsChange(ev) {
      this.serachGroup = "";
      this.userName = "";
      this.peoleOptions = [];
      this.allChooseFlag = false;
      if (ev == "1") {
        //查询组织树
        this.getOrgTreeList();
      } else {
        //查询人员分组
        this.getGroupList();
      }
    },

    //选择组
    groupCheck(index, item) {
      this.groupIndex = index;
      this.groupName = item;
      this.getGroupUserList();
    },

    //树展开事件
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },

    //树选择事件
    onSelect(selectedKeys, el) {
      let { id } = el.node.dataRef;
      this.selectedKeys = [id];
      this.orgId = id;
      this.getOrgUserList();
    },
    //查询分组
    filterGroup() {
      this.getGroupList();
    },
    //查询组织树列表
    getOrgTreeList() {
      this.orgGroupLoading = true;
      return new Promise((resolve, reject) => {
        let { tenantCode } = this.form;
        getOrganizationTreeList({ tenantCode })
          .then((res) => {
            let { data } = res;
            this.treeData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              data?.result || [],
              "childs"
            );
            resolve();
          })
          .catch((_) => {
            this.treeData = [];
            reject();
          })
          .finally((_) => {
            this.orgGroupLoading = false;
            this.peoleOptions = [];
            this.selectedKeys = [];
            this.expandedKeys = [];
          });
      });
    },
    //查询组织树-人员列表
    getOrgUserList() {
      this.userListLoading = true;
      return new Promise((resolve, reject) => {
        let { orgId, userName } = this;
        getOrganizationUserList({ orgId, userName })
          .then((res) => {
            let { data } = res;
            this.peoleOptions = data?.result?.rows || [];
            this.peoleOptions.forEach((v) => {
              let { userName, id } = v;
              v.label = userName;
              v.value = id;
            });
            this.disabledUserList();
            resolve();
          })
          .catch((_) => {
            this.peoleOptions = [];
            reject();
          })
          .finally((_) => {
            this.userListLoading = false;
          });
      });
    },
    //查询人员分组
    getGroupList() {
      this.orgGroupLoading = true;
      return new Promise((resolve, reject) => {
        let { tenantCode } = this.form;
        let { serachGroup } = this;
        getGroupList({ tenantCode, groupName: serachGroup })
          .then((res) => {
            let { data } = res;
            this.groupData = data?.result || [];
            resolve();
          })
          .catch((_) => {
            this.groupData = [];
            reject();
          })
          .finally((_) => {
            this.groupIndex = null;
            this.orgGroupLoading = false;
          });
      });
    },
    //查询人员分组-人员列表
    getGroupUserList() {
      this.userListLoading = true;
      return new Promise((resolve, reject) => {
        let { tenantCode } = this.form;
        let { groupName, userName } = this;
        getGroupUserList({ tenantCode, groupName, userName })
          .then((res) => {
            let { data } = res;
            this.peoleOptions = data?.result || [];
            this.peoleOptions.forEach((v) => {
              let { userName, userId } = v;
              v.label = userName;
              v.value = userId;
            });
            this.disabledUserList();
            resolve();
          })
          .catch((_) => {
            this.peoleOptions = [];
            reject();
          })
          .finally((_) => {
            this.userListLoading = false;
          });
      });
    },

    //禁用人员列表
    disabledUserList() {
      let { activeKey } = this;
      let ids = [];
      if (activeKey == "1") {
        ids = this.hasChoosedUser.map((v) => v.id);
      } else {
        ids = this.hasChoosedUser.map((v) => v.userId);
      }
      this.peoleOptions.forEach((v) => {
        this.$set(v, "disabled", ids.includes(v.value));
      });
    },

    //人员列表搜索
    filterData() {
      if (this.activeKey == "1") {
        //查询组织树-人员列表
        this.getOrgUserList();
      } else {
        //查询分组-人员列表
        this.getGroupUserList();
      }
    },

    //提交
    submit() {
      if (this.hasChoosedUser.length > 0) {
        this.loading = true;
        let { form } = this;
        let formJson = {
          //分组名称
          groupName: "",
          //租户编码
          tenantCode: form.tenantCode,
          //节点id
          nodeId: form.id,
          //人员信息
          users: [],
          //1直接保存；2人员分组+保存
          type: "1",
        };
        this.hasChoosedUser.forEach((item) => {
          formJson.users.push({
            userId: item.value,
            userName: item.label,
          });
        });
        saveOrEditUserConfig(formJson)
          .then((res) => {
            let { data } = res;
            notificationTip("success", "操作成功");
            this.$parent.getTableData();
            this.closeModal();
          })
          .catch((_) => {})
          .finally((_) => {
            this.loading = false;
          });
      }
    },

    // 保存
    save() {
      if (this.hasChoosedUser.length > 0) {
        this.groupNameModalVisible = true;
        let { form, hasChoosedUser } = this;
        this.groupMoadl = {
          //租户编码
          tenantCode: form.tenantCode,
          //节点id
          nodeId: form.id,
          hasChoosedUser: hasChoosedUser || [],
        };
      }
    },

    //关闭弹框
    closeModal() {
      this.$emit("update:visible", false);
      this.form = {
        tenantCode: "",
        name: "",
        id: "",
      };
      this.allChooseFlag = false;
      this.activeKey = "1";
      this.treeData = [];
      this.expandedKeys = [];
      this.checkedKeys = [];
      this.selectedKeys = [];
      this.orgId = "";
      this.serachGroup = "";
      this.groupName = "";
      this.groupData = [];
      this.groupIndex = null;
      this.userName = "";
      this.people = [];
      this.peoleOptions = [];
      this.hasChoosedUser = [];
    },

    //数据移动到右侧
    transferData() {
      let { people, peoleOptions } = this;
      if (people?.length > 0) {
        this.hasChoosedUser = this.hasChoosedUser.concat(
          peoleOptions.filter((v) => people.includes(v.value))
        );
        setTimeout(() => {
          this.disabledUserList();
          this.people = [];
          this.allChooseFlag = false;
        });
      }
    },

    //单个删除已选数据
    removeUser(item) {
      let { activeKey } = this;
      let { id, userId } = item;
      this.peoleOptions.forEach((v) => {
        if (activeKey == "1") {
          if (v.id == id) {
            this.$set(v, "disabled", false);
          }
        } else {
          if (v.userId == userId) {
            this.$set(v, "disabled", false);
          }
        }
      });
      if (activeKey == "1") {
        this.hasChoosedUser = this.hasChoosedUser.filter((v) => v.value != id);
      } else {
        this.hasChoosedUser = this.hasChoosedUser.filter(
          (v) => v.value != userId
        );
      }
    },

    //右侧全部清空
    allClear() {
      this.hasChoosedUser = [];
      this.disabledUserList();
    },

    //左侧全选
    allChoose() {
      let { allChooseFlag, activeKey } = this;
      if (allChooseFlag) {
        let ids = this.hasChoosedUser.map((v) => v.id);
        this.peoleOptions.forEach((v) => {
          if (activeKey == "1") {
            let { id } = v;
            if (!ids.includes(id)) {
              this.people.push(id);
            }
          } else {
            let { userId } = v;
            if (!ids.includes(userId)) {
              this.people.push(userId);
            }
          }
        });
      } else {
        this.people = [];
      }
    },

    //查询已选人员
    getChoosedUser() {
      return new Promise((resolve, reject) => {
        getUserConfigChoosed({ id: this.form.id })
          .then((res) => {
            let { data } = res;
            (data?.result || []).forEach((v) => {
              let { approveUser, approveUserId } = v;
              v.label = approveUser;
              v.value = approveUserId;
              v.id = approveUserId;
              v.userId = approveUserId;
              v.userName = approveUser;
            });
            this.hasChoosedUser = data?.result || [];
            resolve();
          })
          .catch((_) => {
            this.hasChoosedUser = [];
            reject();
          })
          .finally((_) => {});
      });
    },
  },
};
</script>

<style lang="less" scoped>
//弹框
/deep/.modal-container {
  .ant-empty {
    margin: 0;
    height: 93%;
  }
  .ant-modal-body {
    padding: 0;
  }
  .modal-main {
    box-sizing: border-box;
    padding: 20px 60px 40px 60px;
    max-height: 620px;
    .custom-scrollbar();
    .ant-form-item {
      display: flex;
      margin-bottom: 10px;
      .ant-form-item-label {
        width: 90px;
        white-space: pre-wrap;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        height: 36px;
        line-height: 20px;
        label {
          color: #999999;
        }
      }
      .check-item-select {
        height: 86px;
        .ant-select-selection__rendered {
          height: 86px;
          .ant-select-selection__placeholder {
            margin-top: -40px !important;
          }
        }
      }
      .ant-form-item-control-wrapper {
        flex: 1;
      }
    }
    .user-config-modal-body {
      height: 424px;
      .transfer-header {
        width: 100%;
        height: 36px;
        background: #f3f4f6;
        color: #2b2c30;
        padding: 0 10px;
        align-items: center;
        justify-content: space-between;
        flex-shrink: 0;
        .clear-all {
          color: var(--primary-color);
          cursor: pointer;
        }
      }
      .transfer-container {
        flex: 1;
        overflow: hidden;
        .organization,
        .people {
          height: 100%;
          width: 350px;
          .flex();
          flex-direction: column;
          overflow: hidden;
          .filter-data {
            padding: 10px;
            flex-shrink: 0;
            .input {
              height: 36px;
              background: #ffffff;
              border-radius: 4px;
              overflow: hidden;
              border: 1px solid #d4d4d4;
              .bj-icon {
                .flex();
                align-items: center;
                padding: 0 6px;
                cursor: pointer;
              }
              .ant-input {
                flex: 1;
                height: 100%;
                line-height: 36px;
                border: none;
                padding: 0 10px;
                box-shadow: none !important;
              }
            }
          }
          .filter-result {
            flex: 1;
            .custom-scrollbar();
            .group-container {
              padding: 0 10px;
              font-weight: 400;
              font-size: 14px;
              font-family: Microsoft YaHei;
              .group-item {
                color: #2a2b2f;
                cursor: pointer;
                .flex();
                align-items: center;
                height: 28px;
                padding: 0 10px;
                margin-bottom: 8px;
                &:hover {
                  background: #e5f6ff;
                }
              }
              .group-check {
                background: #f5f7fc;
                border-radius: 4px;
                color: var(--primary-color);
              }
            }
          }
        }
        .organization {
          border-right: 1px solid #d4d7d8;
        }
        .people {
          width: 300px;
          .filter-result {
            padding: 0 10px;
            label {
              display: block;
              margin-bottom: 12px;
            }
          }
        }
      }
      .no-choose-container {
        height: 100%;
        flex: 1;
        .flex();
        flex-direction: column;
        border: 1px solid #d4d7d8;
        border-radius: 4px;
        overflow: hidden;
        .ant-tree {
          li {
            width: 100%;
            .ant-tree-node-content-wrapper {
              width: calc(100% - 60px);
            }
          }
        }
      }
      .transfer-button {
        height: 100%;
        width: 70px;
        .flex();
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
        .button {
          width: 46px;
          height: 28px;
          cursor: pointer;
          border-radius: 4px;
          background: var(--primary-color)
            url("https://jszhgd.cn/static/pc/transfer.png") no-repeat center
            center;
          background-size: 14px 10px;
          &.dis {
            background-color: #dcdcdc;
            cursor: not-allowed;
            &:active {
              opacity: 1;
            }
          }
        }
      }
      .choose-container {
        height: 100%;
        width: 300px;
        box-sizing: border-box;
        border: 1px solid #d4d7d8;
        border-radius: 4px;
        flex-shrink: 0;
        .flex();
        flex-direction: column;
        overflow: hidden;
        .transfer-container {
          padding: 10px 10px 0 0;
          .custom-scrollbar();
          .choosed-people {
            float: left;
            min-width: 84px;
            height: 32px;
            background: #f1f2f7;
            border-radius: 4px;
            .flex();
            align-items: center;
            box-sizing: border-box;
            padding: 0 10px;
            color: var(--primary-color);
            margin: 0 0 10px 10px;
            .flex();
            justify-content: space-between;
            .colose {
              width: 12px;
              height: 12px;
              background: var(--primary-color);
              border-radius: 50%;
              .flex();
              align-items: center;
              justify-content: center;
              color: #fff;
              cursor: pointer;
              margin-left: 4px;
              /deep/.bj-icon {
                transform: scale(0.6) translateY(1px);
              }
            }
          }
        }
      }
    }
  }
  .modal-footer {
    text-align: center;
    padding-bottom: 40px;
  }
}
</style>
